package com.managertrade.util.strategy;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

public class YiDaFormFetcher {

    // ✅ 钉钉“企业内部应用”的 AppKey / AppSecret
    private static final String APP_KEY = "dings85hzsigzdhvia7k";
    private static final String APP_SECRET = "bEecBuS2iljdcC5LVSQqg_1ebu4OA2PJqswxZzjQk7JPXanF6OLfuFZNMr1DQbU9";

    // ✅ 宜搭提供的 systemToken（部署运维页面里看到的 API Token）
    private static final String SYSTEM_TOKEN = "HZ966JB1K540HDWKI566RC6CBW7Q25U1HCHHMOHR";

    // ✅ 当前登录用户的 userId（部署运维中也能看到）
    private static final String USER_ID = "012518386764851148372";

    // ✅ 获取 token 的新版钉钉接口
    private static final String GET_TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken";

    // ✅ 获取表单列表接口
    private static final String LIST_FORMS_URL = "https://api.dingtalk.com/v1.0/yida/forms";

    public static void main(String[] args) {
        try {
            disableSslVerification();
            String accessToken = getAccessToken();
            System.out.println("✅ AccessToken: " + accessToken);
            fetchForms(accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳过 SSL 验证（调试用）
     */
    public static void disableSslVerification() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() { return null; }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) { }
                    public void checkServerTrusted(X509Certificate[] certs, String authType) { }
                }
        };
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
    }

    /**
     * ✅ 用新版 API 获取 AccessToken
     */
    public static String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();

        Map<String, String> body = new HashMap<>();
        body.put("appKey", APP_KEY);
        body.put("appSecret", APP_SECRET);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, String>> entity = new HttpEntity<>(body, headers);

        ResponseEntity<String> response = restTemplate.exchange(
                GET_TOKEN_URL,
                HttpMethod.POST,
                entity,
                String.class
        );

        JSONObject json = JSONObject.parseObject(response.getBody());
        String token = json.getString("accessToken");

        if (token == null) {
            throw new RuntimeException("❌ 获取 accessToken 失败: " + response.getBody());
        }
        return token;
    }

    /**
     * ✅ 获取宜搭表单列表
     */
    private static void fetchForms(String accessToken) {
        RestTemplate restTemplate = new RestTemplate();

        String url = LIST_FORMS_URL +
                "?appType=APP_QZ25EW5FNKRRIBE426H0" +
                "&systemToken=" + SYSTEM_TOKEN +
                "&formTypes=FORM" +
                "&pageSize=20" +
                "&pageNumber=1" +
                "&userId=" + USER_ID;

        HttpHeaders headers = new HttpHeaders();
        headers.set("x-acs-dingtalk-access-token", accessToken);
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        System.out.println("✅ 状态码: " + response.getStatusCode());
        System.out.println("✅ 返回内容: " + response.getBody());
    }
}
